//
//  AccountDescListViewController.m
//  quickBatchManager
//
//  Created by 王定波 on 15/10/10.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "TicketListViewController.h"

@interface TicketListViewController ()
{
    NSMutableArray *datalist;
    QbType ticketType;
    long showType;
    UITableView *tableview;
    PMCalendarController *pmCC;
    UICollectionView *collectionview;
    int nowDatePos;
    NSDate *nowDate;
    AAMenuBubbles *payMenu;
    UIPopoverController *popover;
    CategoryModel *category;
    NSMutableArray *allData;
    BOOL isFlag;
}
@end

@implementation TicketListViewController


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    isFlag = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)deleteOrder:(id)sender
{
    NSLog(@"刷新.....");
    [self reloadData];
    [tableview reloadData];
    [self showAlert:@"移动单据成功，请到临时单据编辑"];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(void)initData
{
    nowDate=[NSDate date];
}

-(void)initUI
{
    [self addNavBack];
    UIColor *sbgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"beijingtur"]];
    [self.view setBackgroundColor:sbgColor];
    
    UIImage *image = _bg.image;
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
    _bg.image=image;
    
    _mainView.backgroundColor=[UIColor clearColor];
    
    self.view.frame=CGRectMake(0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT);
    [_kfbtn bk_whenTapped:^{
        [self setBtnSelected:QbTypeSale];
        [_maoliBtn setHidden:NO];
        [_payType setHidden:NO];
        
    }];
    
    [_gysbtn bk_whenTapped:^{
        [self setBtnSelected:QbTypeBuy];
        [_maoliBtn setHidden:YES];
        [_payType setHidden:YES];
        
    }];
    
    [_dbbtn bk_whenTapped:^{
        [self setBtnSelected:QbTypeAllocate];
        [_maoliBtn setHidden:YES];
        [_payType setHidden:YES];
        
    }];
    
    
    
    [_startDateBtn bk_whenTapped:^{
        nowDatePos=1;
        pmCC = [[PMCalendarController alloc] initWithThemeName:@"default"];
        pmCC.delegate = self;
        pmCC.mondayFirstDayOfWeek = NO;
        if ([pmCC isCalendarVisible])
        {
            [pmCC dismissCalendarAnimated:NO];
        }
        [pmCC presentCalendarFromRect:CGRectMake(_startDateBtn.superview.frame.origin.x-60, _startDateBtn.superview.frame.origin.y+40, _startDateBtn.superview.frame.size.width, _startDateBtn.superview.frame.size.height)
                               inView:self.view
             permittedArrowDirections:PMCalendarArrowDirectionAny
                            isPopover:YES
                             animated:YES];
         pmCC.period = [PMPeriod oneDayPeriodWithDate:nowDate];
        
    }];
    
    [_searchBtn bk_whenTapped:^{
         [self reloadData];
        if(ticketType==QbTypeBuy)
        {
            SearchAddProductViewController *detailsVC = [[SearchAddProductViewController alloc] init];
            detailsVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            detailsVC.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
            self.definesPresentationContext = YES;
            detailsVC.delegate = self;
            [self presentViewController:detailsVC animated:YES completion:nil];
        }else
        {
            SearchTicketController *detailsVC = [[SearchTicketController alloc] init];
            detailsVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            detailsVC.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
            self.definesPresentationContext = YES;
            detailsVC.delegate = self;
            [self presentViewController:detailsVC animated:YES completion:nil];
        }
       
       
        
    }];

    
    [_endDateBtn bk_whenTapped:^{
        nowDatePos=2;
        pmCC = [[PMCalendarController alloc] initWithThemeName:@"default"];
        pmCC.delegate = self;
        pmCC.mondayFirstDayOfWeek = NO;
        if ([pmCC isCalendarVisible])
        {
            [pmCC dismissCalendarAnimated:NO];
        }
      
        
        [pmCC presentCalendarFromRect:CGRectMake(_endDateBtn.superview.frame.origin.x+100, _endDateBtn.superview.frame.origin.y+40, _endDateBtn.superview.frame.size.width, _endDateBtn.superview.frame.size.height)
                               inView:self.view
             permittedArrowDirections:PMCalendarArrowDirectionAny
                            isPopover:YES
                             animated:YES];
        
        pmCC.period = [PMPeriod oneDayPeriodWithDate:nowDate];
        
        
    }];
    
    [_payType bk_whenTapped:^{
        
        if(isFlag)
        {
            isFlag = NO;
            if(payMenu) {
                payMenu = nil;
            }
            payMenu = [[AAMenuBubbles alloc] initWithPoint:CGPointMake(_payType.center.x+5, _payType.center.y+55) radius:90 andBubbles:[[NSString stringWithFormat:@"%@%@",[CoreArchive strForKey:NSDEFAULT_ST_PAYMENT],[CoreArchive boolForKey:NSDEFAULT_ST_PAYMENT_DS ]?@"|代收":@""] componentsSeparatedByString:@"|"] inView:self.view];
            payMenu.bubbleRadius = 30;
            payMenu.delegate=self;
            [payMenu show];
          
        }else
        {
            isFlag = YES;
            [_payType setTitle:@"付款方式" forState:UIControlStateNormal];
            [self reloadData];
            
        }
        
        
    }];
    
    [_categoryBtn bk_whenTapped:^{
        ChooseCategoryController *menuVc=[[ChooseCategoryController alloc]init];
        menuVc.delegate=self;
        popover=[[UIPopoverController alloc]initWithContentViewController:menuVc];
        popover.popoverContentSize=CGSizeMake(200, 300);
        [popover presentPopoverFromRect:CGRectMake(40, 20, 10, 10) inView:_categoryBtn permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }];
    
    
    [_reportbtn bk_whenTapped:^{
        ReportViewController *reportVc = [[ReportViewController alloc] init];
        [self.navigationController pushViewController:reportVc animated:YES];
    }];
    
    
    [_shareBtn bk_whenTapped:^{
        [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeImage;
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:UM_KEY
                                          shareText:nil
                                         shareImage:[ToolUtils snapshot:self.mainView]
                                    shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline]
                                           delegate:nil];
    }];
    

    [_startDateBtn setTitle:[[NSDate date] dateStringWithFormat:@"yyyy.MM.dd"] forState:UIControlStateNormal];
    [_endDateBtn setTitle:[[NSDate date] dateStringWithFormat:@"yyyy.MM.dd"] forState:UIControlStateNormal];
    
    [_remarkField setDelegate:self];
    
    
    [self setBtnSelected:QbTypeSale];
    
    [_mainSegment setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.06 green:0.64 blue:0.78 alpha:1]] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    
    [_mainSegment setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.84 green:0.81 blue:0.79 alpha:1]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [_mainSegment setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithWhite:0.4 alpha:1]} forState:UIControlStateNormal];
    
    [_mainSegment setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    
    
    [_mainSegment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    [self segmentAction:_mainSegment];
    
    
    
    
}


-(void)segmentAction:(UISegmentedControl *)Seg{
    NSInteger Index = Seg.selectedSegmentIndex;
    for (UIView *view in _ListView.subviews) {
        [view removeFromSuperview];
    }
  
    [_payType setTitle:@"付款方式" forState:UIControlStateNormal];
    showType=Index;
    
    if(Index==0)
    {
        _categoryBtn.hidden=YES;
        UILabel *title1=[[UILabel alloc] init];
        title1.text=@"日期";
        title1.backgroundColor=[UIColor colorWithRed:0.77 green:0.76 blue:0.73 alpha:1];
        title1.textColor=[UIColor colorWithRed:0.49 green:0.40 blue:0.30 alpha:1];
        title1.textAlignment=NSTextAlignmentCenter;
        title1.font=[UIFont systemFontOfSize:17];
        title1.translatesAutoresizingMaskIntoConstraints = NO;
        
        
        [_ListView addSubview:title1];
        
        
        
        UILabel *title2=[[UILabel alloc] init];
        title2.text=(ticketType==QbTypeBuy?@"款号":@"电话");
        title2.backgroundColor=title1.backgroundColor;
        title2.textColor=title1.textColor;
        title2.textAlignment=title1.textAlignment;
        title2.font=title1.font;
        title2.translatesAutoresizingMaskIntoConstraints = NO;
        
        
        [_ListView addSubview:title2];
        
        
        UILabel *title3=[[UILabel alloc] init];
        title3.text=(ticketType==QbTypeBuy?@"数量":@"客户");
        title3.backgroundColor=title1.backgroundColor;
        title3.textColor=title1.textColor;
        title3.textAlignment=title1.textAlignment;
        title3.font=title1.font;
        title3.translatesAutoresizingMaskIntoConstraints = NO;
        
        [_ListView addSubview:title3];
        
        
        UILabel *title4=[[UILabel alloc] init];
        title4.text=(ticketType==QbTypeBuy?@"进价":@"数量");;
        title4.backgroundColor=title1.backgroundColor;
        title4.textColor=title1.textColor;
        title4.textAlignment=title1.textAlignment;
        title4.font=title1.font;
        title4.translatesAutoresizingMaskIntoConstraints = NO;
        
        
        [_ListView addSubview:title4];
        
        
        
        UILabel *title5=[[UILabel alloc] init];
        title5.text=@"金额";
        title5.backgroundColor=title1.backgroundColor;
        title5.textColor=title1.textColor;
        title5.textAlignment=title1.textAlignment;
        title5.font=title1.font;
        title5.translatesAutoresizingMaskIntoConstraints = NO;
        
        
        [_ListView addSubview:title5];
        
        
        UILabel *title6=[[UILabel alloc] init];
        title6.text=@"备注";
        title6.backgroundColor=title1.backgroundColor;
        title6.textColor=title1.textColor;
        title6.textAlignment=title1.textAlignment;
        title6.font=title1.font;
        title6.translatesAutoresizingMaskIntoConstraints = NO;
        
        [_ListView addSubview:title6];
        
        
        //设置自动布局
        
        [self setEdge:title1.superview firstView:title1 secondView:title1.superview attr:NSLayoutAttributeTop constant:0];
        
        [self setEdge:title1.superview firstView:title1 secondView:title1.superview attr:NSLayoutAttributeLeft constant:0];
        
        [self setEdge:title6.superview firstView:title6 secondView:title6.superview attr:NSLayoutAttributeRight constant:0];
        
        
        
        
        //等宽高
        
        [self setEdge:_ListView firstView:title2 secondView:title1 attr:NSLayoutAttributeWidth constant:0];
        [self setEdge:_ListView firstView:title3 secondView:title1 attr:NSLayoutAttributeWidth constant:0];
        [self setEdge:_ListView firstView:title4 secondView:title1 attr:NSLayoutAttributeWidth constant:0];
        [self setEdge:_ListView firstView:title5 secondView:title1 attr:NSLayoutAttributeWidth constant:0];
        [self setEdge:_ListView firstView:title6 secondView:title1 attr:NSLayoutAttributeWidth constant:0];
        
        
        [self setEdge:_ListView firstView:title2 secondView:title1 attr:NSLayoutAttributeHeight constant:0];
        [self setEdge:_ListView firstView:title3 secondView:title1 attr:NSLayoutAttributeHeight constant:0];
        [self setEdge:_ListView firstView:title4 secondView:title1 attr:NSLayoutAttributeHeight constant:0];
        [self setEdge:_ListView firstView:title5 secondView:title1 attr:NSLayoutAttributeHeight constant:0];
        [self setEdge:_ListView firstView:title6 secondView:title1 attr:NSLayoutAttributeHeight constant:0];
        
        
        
        
        [_ListView addConstraint:[NSLayoutConstraint constraintWithItem:title1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:title2 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]];
        [_ListView addConstraint:[NSLayoutConstraint constraintWithItem:title2 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:title3 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]];
        [_ListView addConstraint:[NSLayoutConstraint constraintWithItem:title3 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:title4 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]];
        [_ListView addConstraint:[NSLayoutConstraint constraintWithItem:title4 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:title5 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]];
        [_ListView addConstraint:[NSLayoutConstraint constraintWithItem:title5 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:title6 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]];
        
        
        [self setEdge:_ListView firstView:title2 secondView:title1 attr:NSLayoutAttributeCenterY constant:0];
        [self setEdge:_ListView firstView:title3 secondView:title1 attr:NSLayoutAttributeCenterY constant:0];
        [self setEdge:_ListView firstView:title4 secondView:title1 attr:NSLayoutAttributeCenterY constant:0];
        [self setEdge:_ListView firstView:title5 secondView:title1 attr:NSLayoutAttributeCenterY constant:0];
        [self setEdge:_ListView firstView:title6 secondView:title1 attr:NSLayoutAttributeCenterY constant:0];
        [self setEdge:_ListView firstView:title1 secondView:nil attr:NSLayoutAttributeHeight constant:40];
        
        
        tableview=[[UITableView alloc] init];
        tableview.backgroundColor=[UIColor clearColor];
        tableview.translatesAutoresizingMaskIntoConstraints = NO;
        if(ticketType==AccountTypeSupplier)
            tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        tableview.delegate=self;
        tableview.dataSource=self;
        [_ListView addSubview:tableview];
        
        [self setEdge:tableview.superview firstView:tableview secondView:tableview.superview attr:NSLayoutAttributeTop constant:40];
        
        [self setEdge:tableview.superview firstView:tableview secondView:tableview.superview attr:NSLayoutAttributeBottom constant:0];
        
        [self setEdge:tableview.superview firstView:tableview secondView:tableview.superview attr:NSLayoutAttributeLeft constant:0];
        
        [self setEdge:tableview.superview firstView:tableview secondView:tableview.superview attr:NSLayoutAttributeRight constant:0];
        
        
    }
    else
    {
        _categoryBtn.hidden=NO;
        UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
        collectionview  =[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)collectionViewLayout:flowLayout];
        
        collectionview.delegate=self;
        collectionview.dataSource=self;
        collectionview.backgroundColor=[UIColor clearColor];
        collectionview.translatesAutoresizingMaskIntoConstraints = NO;
        if(Index==2)
            [collectionview registerClass:[ImageCell class] forCellWithReuseIdentifier:@"ImageCell"];
        else  [collectionview registerClass:[ProductTableCell class] forCellWithReuseIdentifier:@"ProductTableCell"];
        
        
        [_ListView addSubview:collectionview];
        [self setEdge:collectionview.superview firstView:collectionview secondView:collectionview.superview attr:NSLayoutAttributeTop constant:0];
        [self setEdge:collectionview.superview firstView:collectionview secondView:collectionview.superview attr:NSLayoutAttributeBottom constant:0];
        [self setEdge:collectionview.superview firstView:collectionview secondView:collectionview.superview attr:NSLayoutAttributeLeft constant:0];
        
        [self setEdge:collectionview.superview firstView:collectionview secondView:collectionview.superview attr:NSLayoutAttributeRight constant:0];
        
        
    }
    
    [self reloadData];
    
    [self setTotalLabelText:ticketType andIndex:showType];
}


-(void)setBtnSelected:(QbType)type
{
    
    ticketType=type;
    _kfbtn.selected=(type==QbTypeSale?YES:NO);
    _gysbtn.selected=(type==QbTypeBuy?YES:NO);
    _dbbtn.selected=(type==QbTypeAllocate?YES:NO);
    [self reloadData];
    [self setTotalLabelText:ticketType andIndex:0];
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(ticketType==QbTypeBuy)
    {
        
        BatchProductModel *data=[datalist objectAtIndex:indexPath.row];
        
         if([data isKindOfClass:[BatchProductModel class]])
         {
             NSArray *list=[AddProductModel searchWithWhere:@{@"batchId":[ToolUtils numberToStr:data.batchId]} orderBy:nil groupBy:@"productId" offset:0 count:0];
             
             return 40*(list.count+1)+10;
         }
        return 100;
       
    }
    else
        return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return datalist.count;
     }


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    id data=[datalist objectAtIndex:indexPath.row];
    
     if([data isKindOfClass:[SaleOrderModel class]])
     {
         OrderDetailsViewController *detailsVC = [[OrderDetailsViewController alloc] init];
         detailsVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
         detailsVC.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
         self.definesPresentationContext = YES;
         detailsVC.saleOrder = data;
         detailsVC.delegate  = self;
         detailsVC.isEdit = YES;
         [self presentViewController:detailsVC animated:YES completion:nil];
     }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(showType==0)
    {
        
        if(ticketType==QbTypeBuy)
        {
            NSString *reuseIdetify = @"TicketBatchViewCell";
            TicketBatchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
            if(!cell){
                cell=[[TicketBatchViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdetify];
                
            }
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.backgroundColor=[UIColor clearColor];
            
            if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsZero];
                
            }
            if ([cell respondsToSelector:@selector(setLayoutMargins:)])  {
                [cell setLayoutMargins:UIEdgeInsetsZero];
            }
            
            cell.parentVc=self;
            [cell setNeedsUpdateConstraints];
            [cell updateConstraintsIfNeeded];
            [cell setData:[datalist objectAtIndex:indexPath.row]];
            
            return cell;
        }
        else
        {
            NSString *reuseIdetify = @"TicketOrderViewCell";
            TicketOrderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
            if(!cell){
                
                
                NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"TicketOrderViewCell" owner:self options:nil];
                for(id oneObject in nib){
                    if([oneObject isKindOfClass:[TicketOrderViewCell class]]){
                        cell = (TicketOrderViewCell *) oneObject;
                    }
                }
                
            }
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.backgroundColor=[UIColor clearColor];
            
            if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsZero];
                
            }
            if ([cell respondsToSelector:@selector(setLayoutMargins:)])  {
                [cell setLayoutMargins:UIEdgeInsetsZero];
            }
            
            
            
            [cell setData:[datalist objectAtIndex:indexPath.row]];
            
            
            
            return cell;
            
        }
        
    }
    else return nil;
    
    
}


-(void)reloadData
{
    
    allData=[[NSMutableArray alloc] init];
    datalist=[[NSMutableArray alloc]init];
    
   if(ticketType==QbTypeBuy)
    {
        allData=[AppService getBatchListByDate:[_startDateBtn.titleLabel.text replaceCharcter:@"." withCharcter:@"-"] andEndDate:[_endDateBtn.titleLabel.text replaceCharcter:@"." withCharcter:@"-"]];
    }
   else
   {
       allData=[AppService getOrderListByDate:ticketType andStartDate:[_startDateBtn.titleLabel.text replaceCharcter:@"." withCharcter:@"-"] andEndDate:[_endDateBtn.titleLabel.text replaceCharcter:@"." withCharcter:@"-"]];
       
       for (int i=0;i<allData.count;i++) {
           SaleOrderModel *object = allData[i];
           if(!object.isArchive)
           {
               [allData removeObjectAtIndex:i];
           }
       }

   }
    
    
    if(showType==0)
    {
        [tableview reloadData];
        datalist=allData;
        [tableview reloadData];
    }
    else if(showType==2)
    {
        [collectionview reloadData];
        
        BACK(^{
            
           if(ticketType==QbTypeBuy)
            {
                NSMutableArray *batchlist=[[NSMutableArray alloc] init];
                for (BatchProductModel *object in allData) {
                    [batchlist addObject:[ToolUtils numberToStr:object.batchId]];
                }
                datalist=[AddProductModel searchWithWhere:@{@"batchId":batchlist} orderBy:nil groupBy:@"productId" offset:0 count:0];
            }
            else
            {
                NSMutableArray *batchlist=[[NSMutableArray alloc] init];
                for (SaleOrderModel *object in allData) {
                    [batchlist addObject:[ToolUtils numberToStr:object.saleOrderId]];
                }
                datalist=[SaleOrderInfoModel searchWithWhere:@{@"saleOrderId":batchlist} orderBy:nil groupBy:@"productId" offset:0 count:0];
            }
            
            MAIN(^{
                [collectionview reloadData];
            });
            
        });
    }
    else if(showType==1)
    {
        [collectionview reloadData];
        
        BACK((^{
            
            if(ticketType==QbTypeSale || ticketType==QbTypeAllocate)
            {
                NSMutableArray *batchlist=[[NSMutableArray alloc] init];
                for (SaleOrderModel *object in allData) {
                    [batchlist addObject:[ToolUtils numberToStr:object.saleOrderId]];
                }

                
                NSMutableArray *tlist=[[NSMutableArray alloc] init];
                NSArray *plist=[SaleOrderInfoModel searchWithWhere:@{@"saleOrderId":batchlist} orderBy:nil groupBy:@"productId" offset:0 count:0];
                
                datalist=tlist;
                
                for (SaleOrderInfoModel *data in plist) {
                    NSMutableArray *p1=[[NSMutableArray alloc] init];
                    TableModel *model=[[TableModel alloc] init];
                    model.tableList=p1;
                    model.modelTitle=data.product.modelNo;
                    model.totalTitle=[NSString stringWithFormat:@"共计：%0.f",[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}]];
                    model.modelNo = data.product.modelNo;
                    model.remark = data.saleOrder.remark;
                    model.payType = data.saleOrder.payType;
                    if(data.saleOrder.client)
                    {
                        model.clientName = data.saleOrder.client.clientName;
                    }else
                    {
                        model.clientName = data.saleOrder.clientName;
                    }
                    
                    model.orderNumber = data.saleOrder.saleOrderNo;
                    model.productNumber = [SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}];
                    model.totalPrices = [SaleOrderInfoModel sumWithWhere:@"price" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}];
                    [tlist addObject:model];
                    
                    
                    NSDictionary *colorsizeDic=[AppService getSizeAndColorByModel:data.product.modelNo];
                    NSArray *sizeList=colorsizeDic[@"size"];
                    NSArray *colorList=colorsizeDic[@"color"];
                    
                    for (int i=0; i<=colorList.count; i++) {
                        NSMutableArray *p2=[[NSMutableArray alloc] init];
                        [p1 addObject:p2];
                        for (int j=0; j<=sizeList.count; j++)
                        {
                            if(i==0 && j==0)
                            {
                                [p2 addObject:@"颜色"];
                            }
                            else if(i==0)
                            {
                                [p2 addObject:[sizeList objectAtIndex:j-1]];
                            }
                            else if(j==0)
                            {
                                [p2 addObject:[colorList objectAtIndex:i-1]];
                            }
                            else  {
                                [p2 addObject:[ToolUtils numberToStr:[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId],@"sizeName":[sizeList objectAtIndex:i-1],@"colorName":[colorList objectAtIndex:i-1]}]]];
                            }
                        }
                    }
                    
                }
                
                
            }
            else if(ticketType==QbTypeBuy)
            {
                NSMutableArray *batchlist=[[NSMutableArray alloc] init];
                for (BatchProductModel *object in allData) {
                    [batchlist addObject:[ToolUtils numberToStr:object.batchId]];
                }
                
                
                NSMutableArray *tlist=[[NSMutableArray alloc] init];
                NSArray *plist=[AddProductModel searchWithWhere:@{@"batchId":batchlist} orderBy:nil groupBy:@"productId" offset:0 count:0];
                
                datalist=tlist;
                
                for (AddProductModel *data in plist) {
                    NSMutableArray *p1=[[NSMutableArray alloc] init];
                    TableModel *model=[[TableModel alloc] init];
                   
                    model.tableList=p1;
                    model.modelTitle=data.product.modelNo;
                    model.totalTitle=[NSString stringWithFormat:@"共计：%0.f",[AddProductModel sumWithWhere:@"productNumber" where:@{@"batchId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}]];
                    
                    model.modelNo = data.product.modelNo;
                    model.supperName = data.batchProduct.supplier.contactName;
                    model.remark = data.batchProduct.remark;
                    model.productNumber = [AddProductModel sumWithWhere:@"productNumber" where:@{@"batchId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}];
                    model.totalPrices = [SaleOrderInfoModel sumWithWhere:@"price" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}];
                    model.payType = data.batchProduct.payType;
                    [tlist addObject:model];
                    
                    
                    NSDictionary *colorsizeDic=[AppService getSizeAndColorByModel:data.product.modelNo];
                    
                    NSArray *sizeList=colorsizeDic[@"size"];
                    NSArray *colorList=colorsizeDic[@"color"];
                    
                    for (int i=0; i<=colorList.count; i++) {
                        NSMutableArray *p2=[[NSMutableArray alloc] init];
                        [p1 addObject:p2];
                        for (int j=0; j<=sizeList.count; j++)
                        {
                            if(i==0 && j==0)
                            {
                                [p2 addObject:@"颜色"];
                            }
                            else if(i==0)
                            {
                                [p2 addObject:[sizeList objectAtIndex:j-1]];
                            }
                            else if(j==0)
                            {
                                [p2 addObject:[colorList objectAtIndex:i-1]];
                            }
                            else  {
                                [p2 addObject:[ToolUtils numberToStr:[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId],@"sizeName":[sizeList objectAtIndex:i-1],@"colorName":[colorList objectAtIndex:i-1]}]]];
                            }
                        }
                    }
                    
                }
                
            }
            
            MAIN(^{
                [collectionview reloadData];
            });
            
        }));
    }
}



-(void)didChange:(ChangeType)type andData:(id)data
{
    [self reloadData];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return datalist.count;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(showType==2)
    {
        static NSString * CellIdentifier = @"ImageCell";
        ImageCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.backgroundColor=[UIColor clearColor];
        
        [cell setData:[datalist objectAtIndex:indexPath.row]];
        return cell;
        
    }
    
    else if(showType==1)
    {
        static NSString *reuseIdetify = @"ProductTableCell";
        ProductTableCell  *tableCell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdetify forIndexPath:indexPath];
        [tableCell setData:[datalist objectAtIndex:indexPath.row]];
        
        return tableCell;
    }
    
    return nil;
}


#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(showType==2)
        return CGSizeMake(140, 190);
    else {
        TableModel *model=[datalist objectAtIndex:indexPath.row];
        return CGSizeMake(305, (model.tableList.count+2)*35);
    }
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark PMCalendarControllerDelegate methods

- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
    nowDate=newPeriod.startDate;
    if(nowDatePos==1)
    [_startDateBtn setTitle:[NSString stringWithFormat:@"%@",[newPeriod.startDate dateStringWithFormat:@"yyyy.MM.dd"]] forState:UIControlStateNormal];
    else [_endDateBtn setTitle:[NSString stringWithFormat:@"%@",[newPeriod.startDate dateStringWithFormat:@"yyyy.MM.dd"]] forState:UIControlStateNormal];
    
    [self reloadData];
    
    
}



-(void)didSelectData:(ChooseType)type andData:(id)selectData
{
    
    if(type==ChooseTypeCategory)
    {
        category=(CategoryModel*)selectData;
        [_categoryBtn setTitle:category.categoryName forState:UIControlStateNormal];
        [popover dismissPopoverAnimated:YES];
    }
}


#pragma mark-AAMenuBubblesDelegate
-(void)AAMenuBubbles:(AAMenuBubbles *)shareBubbles andIndex:(int)index
{
    [self reloadData];
    [_payType setTitle:payMenu.bubblestrs[index] forState:UIControlStateNormal];
    [self searchPayType:index];
}


-(void)setTotalLabelText:(QbType) type andIndex:(int)index
{
    if(type == QbTypeSale)
    {
         NSLog(@"type===qqq=%d",type);
        if(datalist && [datalist count]>0)
        {
            int number = 0;
            int diaoboNumber = 0;
            int tuiNumber = 0;
            for (int i=0;i<datalist.count;i++) {
                SaleOrderModel *mode = [datalist objectAtIndex:i];
                number += mode.totalNumber;
                if(mode.client)
                {
                    if(mode.client.clientType==1)
                    {
                        diaoboNumber+=mode.totalNumber;
                    }
                }
                
                NSMutableArray *productInfos = [SaleOrderInfoModel searchWithWhere:[NSString stringWithFormat:@""] orderBy:nil offset:0 count:0];
                for (SaleOrderInfoModel *modelInfo in productInfos) {
                    if(modelInfo.productNumber<0)
                    {
                        tuiNumber+=modelInfo.productNumber;
                    }
                }
            }
        if(index==0)
        {
            _totalLabel.text = [NSString stringWithFormat:@"出货:%d件 退换:%d件 调拨:%d件",number,tuiNumber,diaoboNumber];
        }else
        {
             _totalLabel.text = [NSString stringWithFormat:@"出库:%d件 退换:%d件",number,tuiNumber];
        }
        
    }
    }else if(type==QbTypeBuy)
    {
         NSLog(@"type===入库=%d",type);
        _totalLabel.text  = @"入库0件";
        if(allData &&[allData count]>0)
        {
            int number = 0;
            for (BatchProductModel *model in allData) {
                NSLog(@"数量:%f",model.totalNumber);
                number +=model.totalNumber;
            }
            _totalLabel.text  = [NSString stringWithFormat:@"入库:%d件",number];
        }
        
    }else if(type==QbTypeAllocate)
    {
         _totalLabel.text  = @"";
    }
}










#pragma mark --delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(datalist && [datalist count]>0)
    {
        if([textField.text isValid])
        {
            [self searchRemark:textField.text];
        }
    }
    [textField resignFirstResponder];
    return YES;
}


-(void)searchResult:(NSMutableDictionary *)searchWhere
{
      NSLog(@"1datalist size:%lu",(unsigned long)[datalist count]);
    NSString *modeNo = [searchWhere objectForKey:@"modelNo"];
    NSString *clientName = [searchWhere objectForKey:@"clientName"];
    NSString *orderNumber = [searchWhere objectForKey:@"orderNumber"];
    NSString *number = [searchWhere objectForKey:@"number"];
    NSString *money = [searchWhere objectForKey:@"money"];
    if([modeNo isValid] || [clientName isValid] || [orderNumber isValid] || [number isValid] || [money isValid])
    {
        if(datalist && [datalist count]>0)
        {
            NSObject *obj = [datalist objectAtIndex:0];
        
            if([obj isKindOfClass:[SaleOrderModel class]])
            {
                for (int i=0;i<[datalist count];++i) {
                    SaleOrderModel *model = [datalist objectAtIndex:i];
                    NSMutableArray *infoModels = [SaleOrderInfoModel searchWithWhere:[NSString stringWithFormat:@"saleOrderId=%ld",(long)model.saleOrderId] orderBy:nil offset:0 count:0];
                    
                    BOOL isDelete = NO;
                    if([modeNo isValid])
                    {
                        for (SaleOrderInfoModel *infoModel in infoModels) {
                            if(![infoModel.product.modelNo isEqualToString:modeNo])
                            {
                                isDelete = YES;
                            }
                        }
                    }
                    if ([clientName isValid])
                    {
                        if(![clientName isEqualToString:model.clientName])
                        {
                                 isDelete = YES;
                        }
                    }
                    if ([orderNumber isValid])
                    {
                        if(![orderNumber isEqualToString:model.saleOrderNo])
                        {
                                  isDelete = YES;
                        }
                        
                    }
                    if ([number isValid])
                    {
                        if(!([number integerValue]==model.totalNumber))
                        {
                                 isDelete = YES;
                        }
                        
                    }
                    if ([money isValid])
                    {
                        if(!([money integerValue]==model.totalPrice))
                        {
                               isDelete = YES;
                        }
                    }
                    
                    if(isDelete)
                    {
                        --i;
                        [datalist removeObject:model];
                    }
                    
                    [tableview reloadData];
                    
                }
            }
            
            
            ///==================
            if([obj isKindOfClass:[AddProductModel class]])
            {
                NSLog(@"AddProductModel datalist size:%d",[datalist count]);
                //入库
            }
            if([obj isKindOfClass:[SaleOrderInfoModel class]])
            {
                
                for (int i=0;i<[datalist count];++i) {
                    
                    SaleOrderInfoModel *infoModel = [datalist objectAtIndex:i];
                    BOOL isDelete = NO;
                    if([modeNo isValid])
                    {
                        if(![infoModel.product.modelNo isEqualToString:modeNo])
                        {
                                isDelete =  YES;
                        }
                    }
                    if ([clientName isValid])
                    {
                        if(![infoModel.saleOrder.clientName isEqualToString:clientName])
                        {
                               isDelete =  YES;
                        }
                    }
                    if ([orderNumber isValid])
                    {
                        if(![infoModel.saleOrder.saleOrderNo isEqualToString:orderNumber])
                        {
                              isDelete =  YES;
                        }
                        
                    }
                    if ([number isValid])
                    {
                        if(!(infoModel.saleOrder.totalNumber ==[number integerValue]) )
                        {
                              isDelete =  YES;
                        }
                        
                    }
                    if ([money isValid])
                    {
                        if(!(infoModel.saleOrder.totalPrice ==[money integerValue]) )
                        {
                             isDelete =  YES;
                        }
                        
                    }
                    
                    if(isDelete)
                    {
                        --i;
                        [datalist removeObject:infoModel];
                    }
                    
                    [collectionview reloadData];
                }
                
            }
            
            
             if([obj isKindOfClass:[TableModel class]])
             {
                 for (int i=0;i<[datalist count];++i) {
                     
                     TableModel *tableModel = [datalist objectAtIndex:i];
                     BOOL isDelete = NO;
                     if([modeNo isValid])
                     {
                         if(![tableModel.modelNo isEqualToString:modeNo])
                         {
                             isDelete = YES;
                         }
                     }else if ([clientName isValid])
                     {
                         if(![tableModel.clientName isEqualToString:clientName])
                         {
                             isDelete = YES;
                         }
                     }else if ([orderNumber isValid])
                     {
                         if(![tableModel.orderNumber isEqualToString:orderNumber])
                         {
                             isDelete = YES;
                         }
                         
                     }else if ([number isValid])
                     {
                         if(![[NSNumber numberWithDouble:tableModel.productNumber] integerValue] ==[number integerValue] )
                         {
                             isDelete = YES;
                         }
                         
                     }else if ([money isValid])
                     {
                         if(!(tableModel.totalPrices ==[money integerValue]))
                         {
                            isDelete = YES;
                         }
                         
                     }
                     
                     if(isDelete)
                     {
                         --i;
                         [datalist removeObject:tableModel];
                     }
                     
                     [collectionview reloadData];
                 }

                 
             }
            ///end==================
        }
        
    }
    
    
    
}



-(void)searchAddProductResult:(NSMutableDictionary *)searchWhere
{
    NSString *modeNo = [searchWhere objectForKey:@"modelNo"];
    NSString *supperName = [searchWhere objectForKey:@"supperName"];
    NSString *number = [searchWhere objectForKey:@"number"];
    NSString *money = [searchWhere objectForKey:@"money"];
    if([modeNo isValid] || [supperName isValid] || [number isValid] || [money isValid])
    {
        if(datalist && [datalist count]>0)
        {
            NSObject *obj = [datalist objectAtIndex:0];
            if([obj isKindOfClass:[BatchProductModel class]])
            {
               
                for (int i=0;i<[datalist count];++i) {
                    BatchProductModel *infoModel = [datalist objectAtIndex:i];
                    BOOL isDelete = NO;
                    if([modeNo isValid])
                    {
                       NSArray *list=[AddProductModel searchWithWhere:@{@"batchId":[ToolUtils numberToStr:infoModel.batchId]} orderBy:nil groupBy:@"productId" offset:0 count:0];
                        for (AddProductModel *addModel in list) {
                            if(![addModel.product.modelNo isEqualToString:modeNo])
                            {
                                isDelete = YES;
                            }
                        }
                    }
                    if ([supperName isValid])
                    {
                        if(![infoModel.supplier.contactName isEqualToString:supperName])
                        {
                            isDelete = YES;
                        }
                    }
                    if ([number isValid])
                    {
                        if(!([[NSNumber numberWithDouble:infoModel.totalNumber] integerValue] ==[number integerValue]) )
                        {
                            isDelete = YES;
                        }
                        
                    }
                    if ([money isValid])
                    {
                        if(!(infoModel.totalPrice==[money integerValue]) )
                        {
                            isDelete = YES;
                            
                        }
                        
                    }
                    
                    if(isDelete)
                    {
                        --i;
                        [datalist removeObject:infoModel];
                    }
                    
                    
                }
                
                [tableview reloadData];
            }
            
            if([obj isKindOfClass:[AddProductModel class]])
            {
                for (int i=0;i<[datalist count];++i) {
                    AddProductModel *infoModel = [datalist objectAtIndex:i];
                    BOOL isDelete = NO;
                    if([modeNo isValid])
                    {
                        if(![infoModel.product.modelNo isEqualToString:modeNo])
                        {
                            isDelete = YES;
                        }
                    }
                    if ([supperName isValid])
                    {
                        if(![infoModel.batchProduct.supplier.contactName isEqualToString:supperName])
                        {
                            isDelete = YES;
                        }
                    }
                    if ([number isValid])
                    {
                        if(!(infoModel.productNumber ==[number integerValue]) )
                        {
                            isDelete = YES;
                        }
                        
                    }
                    if ([money isValid])
                    {
                        if(!(infoModel.salePrice==[money doubleValue]) )
                        {
                            isDelete = YES;
                            
                        }
                        
                    }
                    
                    if(isDelete)
                    {
                        --i;
                        [datalist removeObject:infoModel];
                    }
                    
                    
                }
                
                [collectionview reloadData];
            }
            
            if([obj isKindOfClass:[TableModel class]])
            {
                for (int i=0;i<[datalist count];++i) {
                    
                    TableModel *tableModel = [datalist objectAtIndex:i];
                    BOOL isDelete = NO;
                    if([modeNo isValid])
                    {
                        if(![tableModel.modelNo isEqualToString:modeNo])
                        {
                            isDelete = YES;
                        }
                    }
                    if ([supperName isValid])
                    {
                        if(![tableModel.supperName isEqualToString:supperName])
                        {
                            isDelete = YES;
                        }
                    }
                    if ([number isValid])
                    {
                        if(!([[NSNumber numberWithDouble:tableModel.productNumber] integerValue] ==[number integerValue]) )
                        {
                            isDelete = YES;
                        }
                        
                    }else if ([money isValid])
                    {

                        if(!(tableModel.totalPrices ==[money integerValue]) )
                        {
                            isDelete = YES;
                        }
                        
                    }
                    
                    if(isDelete)
                    {
                        --i;
                        [datalist removeObject:tableModel];
                    }
                    
                    [collectionview reloadData];
                }
            }
        }
    }
    
}


-(void)searchRemark:(NSString *)remarkStr
{
 
        if(datalist && [datalist count]>0)
        {
            NSObject *obj = [datalist objectAtIndex:0];
            if([obj isKindOfClass:[BatchProductModel class]])
            {
                
                for (int i=0;i<[datalist count];++i) {
                    BatchProductModel *infoModel = [datalist objectAtIndex:i];
                    if(![infoModel.remark isEqualToString:remarkStr])
                    {
                        --i;
                        [datalist removeObject:infoModel];
                    }
                }
                
                [tableview reloadData];
            }
            
            if([obj isKindOfClass:[AddProductModel class]])
            {
                for (int i=0;i<[datalist count];++i) {
                    AddProductModel *infoModel = [datalist objectAtIndex:i];
                    if(![infoModel.remark isEqualToString:remarkStr])
                    {
                        --i;
                        [datalist removeObject:infoModel];
                    }
                }
                
                [collectionview reloadData];
            }
            
            if([obj isKindOfClass:[TableModel class]])
            {
                for (int i=0;i<[datalist count];++i) {
                    TableModel *tableModel = [datalist objectAtIndex:i];
                    if(![tableModel.remark isEqualToString:remarkStr])
                    {
                        --i;
                        [datalist removeObject:tableModel];
                    }
                    
                    [collectionview reloadData];
                }
            }
            if([obj isKindOfClass:[SaleOrderModel class]])
            {
                for (int i=0;i<[datalist count];++i) {
                    SaleOrderModel *orderModel = [datalist objectAtIndex:i];
                     if(![orderModel.remark isEqualToString:remarkStr])
                     {
                         --i;
                         [datalist removeObject:orderModel];
                     }
                 }
                NSLog(@"查找remark");
                [tableview reloadData];
            }
        }
    
}


-(void)searchPayType:(int)index
{
    if(datalist && [datalist count]>0)
    {
        NSObject *obj = [datalist objectAtIndex:0];
        if([obj isKindOfClass:[SaleOrderModel class]])
        {
            
            for (int i=0;i<[datalist count];++i) {
                SaleOrderModel *orderModel = [datalist objectAtIndex:i];
                if(![orderModel.payType isEqualToString:[NSString stringWithFormat:@"%d",index]])
                {
                    --i;
                    [datalist removeObject:orderModel];
                }
            }
            
            [tableview reloadData];
        }
        
        if([obj isKindOfClass:[SaleOrderInfoModel class]])
        {
            for (int i=0;i<[datalist count];++i) {
                SaleOrderInfoModel *infoModel = [datalist objectAtIndex:i];
                if(![infoModel.saleOrder.payType isEqualToString:[NSString stringWithFormat:@"%d",index]])
                {
                    --i;
                    [datalist removeObject:infoModel];
                }
            }
            
            [collectionview reloadData];
        }
        
        if([obj isKindOfClass:[TableModel class]])
        {
            for (int i=0;i<[datalist count];++i) {
                TableModel *tableModel = [datalist objectAtIndex:i];
                if(![tableModel.payType isEqualToString:[NSString stringWithFormat:@"%d",index]])
                {
                    --i;
                    [datalist removeObject:tableModel];
                }
                
                [collectionview reloadData];
            }
        }
    }
    
}

@end

